package com.javaex.book.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.javaex.book.annotation.Controller;
import com.javaex.book.annotation.RequestMapping;
import com.javaex.book.pojo.Book;
import com.javaex.book.service.BookService;
import com.javaex.book.service.impl.BookServiceImpl;
import com.javaex.book.utils.BeanUtils;
import com.javaex.book.utils.Constants.Code;
import com.javaex.book.utils.Pages;
import com.javaex.book.utils.Pagination;
import com.javaex.book.utils.RequestMethod;
import com.javaex.book.utils.ReturnResult;
import com.javaex.book.utils.TypeConvertUtils;
import com.javaex.book.utils.UploadUtils;
import com.javaex.book.utils.WebUtils;

@Controller()
public class BookController {
	
	private static final Logger logger = LoggerFactory.getLogger(BookController.class);
	private BookService bookService = new BookServiceImpl();
	
	/**
	 * 根据条件获取图书数据
	 * @param req 请求
	 * @return 包含图书数据的分页对象
	 */
	@RequestMapping("/book/list")
	public String bookList(HttpServletRequest req) {
		// 获取页码、页容量、最低价、最高价
		Integer pageNo = WebUtils.getInteger(req, "no", Pagination.DEFAULT_PAGE_NO);
		Integer pageSize = WebUtils.getInteger(req, "size", Pagination.DEFAULT_PAGE_SIZE);
		BigDecimal minPrice = WebUtils.getBigDecimal(req, "min", null);
		BigDecimal maxPrice = WebUtils.getBigDecimal(req, "max", null);
		
		// 查询总记录数
		Integer totalCount = bookService.countBooks(minPrice, maxPrice);
		Pagination pagination = new Pagination(pageNo, pageSize, totalCount);
		req.setAttribute("page", pagination);
		if (totalCount == 0) {
			return Pages.INDEX;
		}
		List<Book> bookList = bookService.queryBookList(pagination, minPrice, maxPrice);
		req.setAttribute("bookList", bookList);
		return Pages.INDEX;
	}
	
	// 前往图书管理页面
	@RequestMapping("/manager/book")
	public String manageBook(HttpServletRequest req) {
		// 获取页码、页容量
		Integer pageNo = WebUtils.getInteger(req, "no", Pagination.DEFAULT_PAGE_NO);
		Integer pageSize = WebUtils.getInteger(req, "size", Pagination.DEFAULT_PAGE_SIZE);
		Integer total = bookService.countBooks(null, null);
		Pagination pagination = new Pagination(pageNo, pageSize, total);
		logger.info("前往图书管理界面: {} {}", Pages.BOOK_MANAGER, pagination);
		List<Book> bookList = bookService.queryBookList(pagination, null, null);
		req.setAttribute("bookList", bookList);
		pagination.setUrl("manager/book");
		req.setAttribute("page", pagination);
		return Pages.BOOK_MANAGER;
	}
	
	// 前往添加图书页面
	@RequestMapping("/manager/book/add")
	public String toAddBook(HttpServletRequest req) {
		logger.info("前往添加图书界面: {}", Pages.BOOK_EDIT);
		return Pages.BOOK_EDIT;
	}
	
	// 添加图书
	@RequestMapping(value = "/manager/book/add", method = RequestMethod.POST)
	public String addBook(HttpServletRequest req) throws Exception {
		Map<String, String> map = UploadUtils.upload(req);
		Book book = BeanUtils.injectDataIntoBean(Book.class, (type, name) -> TypeConvertUtils.typeConvert(type, map.get(name)));
		// 校验数据
		if (book.getName().isEmpty() || book.getAuthor().isEmpty()) {
			req.setAttribute("message", "书名或作者不能为空");
			req.setAttribute("book", book);
			return Pages.redirect(req.getHeader("Referer"));
		}
		// 添加图书
		logger.info("添加图书：{}", book);
		ReturnResult result = bookService.addBook(book);
		if (result.getCode() == Code.FAIL) {
			// 添加失败
			req.setAttribute("message", result.getMessage());
			req.setAttribute("book", book);
			return Pages.redirect(req.getHeader("Referer"));
		}
		// 添加成功
		return Pages.redirect("/book");
	}
	
	// 前往图书修改页面
	@RequestMapping("/manager/book/update")
	public String toUpdateBook(HttpServletRequest req, Map<String, String> params) {
		logger.info("前往图书修改界面: {} bookId={}", Pages.BOOK_EDIT, req.getParameter("id"));
		Book book = bookService.queryBookById(Integer.parseInt(req.getParameter("id")));
		req.setAttribute("title", "修改图书");
		req.setAttribute("book", book);
		return Pages.BOOK_EDIT;
	}
	
	// 修改图书
	@RequestMapping(value = "/manager/book/update", method = RequestMethod.POST)
	public String updateBook(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		Map<String, String> map = UploadUtils.upload(req);
		Book book = BeanUtils.injectDataIntoBean(Book.class, (type, name) -> TypeConvertUtils.typeConvert(type, map.get(name)));
		logger.info("修改图书：{}", book);
		// 校验数据
		if (book.getName().isEmpty() || book.getAuthor().isEmpty()) {
			req.setAttribute("message", "书名或作者不能为空");
			req.setAttribute("book", book);
			return Pages.redirect(req.getHeader("Referer"));
		}
		// 修改图书
		Integer rows = bookService.updateBook(book);
		if (rows == null || rows == 0) {
			// 修改失败
			req.setAttribute("title", "修改图书");
			req.setAttribute("message", "修改失败");
			req.setAttribute("book", book);
			return Pages.BOOK_EDIT;
		}
		return Pages.redirect(map.get("referer"));
	}
	
	// 删除图书
	@RequestMapping("/manager/book/delete")
	public String deleteBook(HttpServletRequest req) {
		Integer id = Integer.parseInt(req.getParameter("id"));
		logger.info("删除图书: id = {}", id);
		Integer rows = bookService.deleteBookById(id);
		if (rows == null || rows == null) {
			req.setAttribute("message", "删除失败，图书ID = " + id);
		}
		return Pages.redirect(req.getHeader("Referer"));
	}
}
